<script lang="ts" setup name="WangEditor">
import { reqAddArticleFromWangEditor, reqGetArticleText, reqUploadFile2ArticleUrl } from '@/api/article'
import { Article } from '@/class/Article'
import router, { RouterName } from '@/router'
import { successMessage, warningMessage } from '@/utils/message'

import { Boot, type IDomEditor } from '@wangeditor/editor'
// @ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { de } from 'element-plus/es/locales.mjs'
import { onBeforeMount, onBeforeUnmount, onMounted, reactive, ref, shallowRef, toRefs, watch } from 'vue'
import { useRoute } from 'vue-router'
//编辑器实例，必须用 shallowRef
let article = reactive(new Article({ id: "01", article: "404" }))
const editorRef = shallowRef();
const mode = ref('simple')// 或 'simple','default'
let isChanged = ref(true)
let uploadImageList = []
// 模拟 ajax 异步获取内容
onBeforeMount(async () => {
  const router = useRoute();
  console.log(router);
  let id = router.query.id
  if (id && typeof id === 'string') {
    Object.assign(article, await Article.getArticleById(id))
  }
  else {
    Object.assign(article, await Article.createArticle())
  }

  editorConfig.MENU_CONF.uploadImage.headers.articleId = article.id;
})
const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: reqUploadFile2ArticleUrl,
      fieldName: 'file',
      // customInsert(res, insertFn) {
      //   insertFn(res.data, "", "").then(result1 => {
      //     saveArticleMethod().then(result2 => {
      //       editArticleMethod()
      //     })
      //   })
      // },
      headers: {
        articleId: ""
      },
      maxFileSize: 100 * 1024 * 1024, // 1M
    },
    insertImage: {
      onInsertedImage: onInsertedImage
    },
    editImage: {
      onUpdatedImage: onEditImage
    }
  }
}
function onInsertedImage(image: any) {
  uploadImageList.push(image)
}
function onEditImage(src: any) {
  console.log("edit" + src)
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

function handleCreated(editor: IDomEditor) {
  editorRef.value = editor // 记录 editor 实例，重要！
}
function handleChange() {
  isChanged.value = true
}
watch(() => article.article, (newValue, oldValue) => {
  handleChange()
})
function save() {
  reqAddArticleFromWangEditor(article).then(() => {
    successMessage("保存成功")
    isChanged.value = false
  })
}
function deleteArticle() {
  article.deleteArticle().then(() => {
    back()
  })
}
function back() {
  router.push({
    name:RouterName.ArticleList
  })
}
</script>
<template>
  <div class="main">
    标题：<el-input v-model="article.title" placeholder="请输入标题" style="width:25%" @change="handleChange"
      class="edit-item"></el-input>
    简介：<el-input v-model="article.intro" placeholder="请输入简介" style="width:25%" @change="handleChange"
      class="edit-item"></el-input>
    <el-button type="primary" @click="back" circle class="edit-item">
      <el-icon>
        <Back />
      </el-icon>
    </el-button>
    <el-button v-if="article.id" type="danger" @click="deleteArticle" circle class="edit-item">
      <el-icon>
        <Delete />
      </el-icon>
    </el-button>

    <el-button :disabled="!isChanged" type="primary" @click="save" circle class="edit-item">
      <el-icon>
        <Finished />
      </el-icon>
    </el-button>
    <Toolbar style="border: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode">
      <button>save</button>
    </Toolbar>
    <Editor style="height: 500px; overflow-y: hidden;" v-model="article.article" :defaultConfig="editorConfig"
      :mode="mode" @onCreated="handleCreated">
    </Editor>
  </div>
</template>
<style>
.main {
  border: 2px solid #ccc;
  border-radius: 5px;
  padding: 5px;
}

.edit-item {
  padding: 5px;
}

.w-e-text-container {
  border: 2px solid #ccc;
  margin: 5px 0;
}
</style>